package web.generatordubboservice;

import exec.GeneratorDubboServiceAll;
import net.sf.json.JSONObject;
import sun.misc.BASE64Decoder;
import utils.StringUtils;
import web.AbstractProcessor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.ArrayList;

/**
 * Created by baolong on 2016/8/25.
 */
public class GeneratorDubboServiceProcessor extends AbstractProcessor {

    @Override
    public void process(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        try{
            String basePath = httpServletRequest.getParameter("basePath");
            String buildproperties = httpServletRequest.getParameter("buildproperties");
            basePath = URLDecoder.decode(new String(new BASE64Decoder().decodeBuffer(basePath),"utf-8"),"utf-8");
            buildproperties = URLDecoder.decode(new String(new BASE64Decoder().decodeBuffer(buildproperties),"utf-8"),"utf-8");

            final String finalBuildProperties = buildproperties;
            GeneratorDubboServiceAll.exec(basePath,new ArrayList<String>(){
                {
                    for(String s : finalBuildProperties.split("\n")){
                        if(StringUtils.isNotEmpty(s)){
                            this.add(s.trim());
                        }
                    }
                }
            });

            JSONObject result = new JSONObject();
            result.put("resCode","0000");
            result.put("resDesc", "成功");
            try {
                httpServletResponse.getOutputStream().write(result.toString().getBytes("utf-8"));
                httpServletResponse.getOutputStream().flush();
                httpServletResponse.getOutputStream().close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject result = new JSONObject();
            result.put("resCode","0002");
            result.put("resDesc", e.getMessage());
            try {
                httpServletResponse.getOutputStream().write(result.toString().getBytes("utf-8"));
                httpServletResponse.getOutputStream().flush();
                httpServletResponse.getOutputStream().close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }
}
